package com.zzl.spark.sql.UDF_UDAF

import org.apache.spark.sql.{Row, SQLContext}
import org.apache.spark.sql.types.{StringType, StructField, StructType}
import org.apache.spark.{SparkConf, SparkContext}

object UDFA {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
      .setMaster("local")
      .setAppName("UDF")
    val sc = new SparkContext(conf)

    val sqlContext = new SQLContext(sc)
    val names = Array("yarn","marry","jack","tom");

    val nameRdd = sc.parallelize(names,4)

    val namesRowRdd = nameRdd.map(n=>Row(n))

    val strucType =StructType(Array(StructField("name",StringType,true)));

    val namesDf = sqlContext.createDataFrame(namesRowRdd,strucType);

    namesDf.createTempView("names")

    sqlContext.udf.register("strLen",(lover:String,str:String)=>lover+"\t"+str.length)

    sqlContext.sql("select name,strLen('I love xuruyun!',name) from names").show()

    sc.stop()
  }
}
